<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <!-- 左侧 -->
        <template v-slot:before>
          共{{ page.total }}条数据
        </template>
        <!-- 右侧 -->
        <template v-slot:after>
          <el-button type="success" @click="$router.push('/import')">execl导入</el-button>
          <el-button type="info" @click="exportDate">execl导出</el-button>
          <el-button type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <!-- 表格组件 -->
      <el-table v-loading="loading" :data="list">
        <el-table-column>
          <el-table-column type="index" label="序号" sortable="" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="头像" align="center">
            <template slot-scope="{row}">
              <img
                v-imageError="require('@/assets/common/head.jpg')"
                :src="row.staffPhoto"
                alt=""
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                @click="showIMG(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="手机号" prop="mobile" sortable="" />
          <el-table-column prop="formOfEmployment" :formatter="formatEmployment" label="聘用形式" sortable="" />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="" />
          <el-table-column prop="enableState" label="账户状态" sortable="">
            <template slot-scope="{row}">
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>

      <!-- y页码 -->
      <el-row type="flex" justify="center" align="middle" style="height:60px">
        <el-pagination layout="prev,pager,next" :page-size="page.size" :total="page.total" @current-change="changePage" />
      </el-row>
    </div>
    <!-- 弹出层 -->
    <AddEmployees :show-dialog.sync="showDialog" />

    <el-dialog title="二维码" :visible.sync="showEWM">
      <el-row type="flex" justify="center">
        <canvas ref="canvas" />
      </el-row>
    </el-dialog>

    <!-- 放置分配组件 -->
    <AssgnRole ref="assgnRole" :show-role-dialog.sync="showRoleDialog" :user-id="userID" />
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployees from './components/add-employees.vue'
import QRcode from 'qrcode'
import AssgnRole from '@/views/employees/components/assgin-role.vue'
export default {
  components: { AddEmployees, AssgnRole },
  data() {
    return {
      list: [], // 用于接收员工列表
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      loading: false, // 显示遮罩层
      showDialog: false,
      showEWM: false,
      showRoleDialog: false, // 显示分配角色的弹层
      userID: null // 定义一个userID
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 获取员工列表
    async getEmployeeList() {
      const { total, rows } = await getEmployeeList(this.page)
      this.page.total = total
      this.list = rows
    },
    // 分页变化
    changePage(newpage) {
      this.page.page = newpage
      this.getEmployeeList()
    },
    // 格式化聘用形式
    formatEmployment(row, column, cellValue, index) {
      const res = EmployeeEnum.hireType.find(obj => obj.id === cellValue)
      return res ? res.value : '未知'
    },

    // 删除员工
    async delEmployee(id) {
      try {
        await this.$confirm('确定删除吗？')
        await delEmployee(id)
        this.$message.success('删除成功')
        this.getEmployeeList()
      } catch (error) {
        console.log(error)
      }
    },

    // 导出excel
    exportDate() {
      const headers = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }

      import('@/vendor/Export2Excel').then(async excel => {
        // 引入文件成功后的导出对象

        // 获取所有数据 total中存储着当前数据条数的总和   用1页获取所有数据
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        const data = this.formatJson(headers, rows)
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: '员工信息表'
        })
      })
    },

    // 定义方法 将对象转化为数组， 并遵循表头的格式
    // [{}] => [[]]
    formatJson(headers, rows) {
      return rows.map(obj => {
        // obj是一个对象
        return Object.keys(headers).map(key => {
          // 需要判断字段
          // if (headers[key] === 'formOfEmployment') {
          //   const obj = EmployeeEnum.hireType.find(item => item.id === obj[headers[key]])
          //   return obj ? obj.value : '未知'
          // }
          return obj[headers[key]]
        })
      })
    },
    showIMG(img) {
      if (img) {
        this.showEWM = true
        this.$nextTick(() => {
          QRcode.toCanvas(this.$refs.canvas, img)
        })
      } else {
        return this.$message.warning('该用户暂且并未上传头像')
      }
    },
    editRole(id) {
      this.userID = id
      this.$refs.assgnRole.getUserDataById(id)
      this.showRoleDialog = true
    }
  }
}
</script>

<style>

</style>
